/**
 * The commonly used factory
 * Facilitate everybody calls
 * Author         suchen
 */
define([
        "dojo/on",
        "dojo/topic",
        "dojo/_base/array",
        "dzdtApp/Util",
        "dzdtApp/dzdtAppConfig"
    ], function (on, topic, array, Util, dzdtAppConfig) {
        return {
            /**
             * project name
             */
            currentGraphic: null,
            name: 'restful',
            sxxfx: {
                '1': '上行',
                '2': '下行',
                '3': '双向',
                '4': '匝道',
                '5': '渡口',
                '6': '其他'
            },
            /**
             * This method is used to jquery.autocomplete the encapsulation of the ajax request
             */
            autoAjax: function (options) {
                var defaults = {
                    url: '/restful/rest/xzqh/auto',
                    id: '#lxbm',
                    width: 212,
                    max: 15,
                    tableName: 'GIS_XZQH',
                    field: 'lxdm,lxmc',
                    conditions: 'xzqhbm,lxbm'
                };

                var opts = $.extend(defaults, options);

                $(opts.id).autocomplete(opts.url, {
                    cacheLength: 1,
                    matchSubset: false,
                    selectFirst: true,
                    minChars: 0,
                    scroll: false,
                    delay: 500,
                    type: "get",
                    dataType: "json",
                    max: opts.max,
                    width: opts.width,
                    extraParams: {
                        field: function () {
                            var xzdj = $('#xzdj').val();
                            if (xzdj == 'Y' || xzdj == 'Z' || xzdj == 'C')  return 'lddm,lxmc';
                            else return opts.field;
                        },
                        tableName: function () {
                            var xzdj = $('#xzdj').val();
                            if (xzdj == 'Y' || xzdj == 'Z' || xzdj == 'C')  return 'GIS_NCLX';
                            else return opts.tableName;
                        },
                        xzdj: function () {
                            var val = $('#xzdj').val();
                            if (val == null) {
                                val = "";
                            }
                            return val;
                        },
                        conditions: function () {
                            var xzdj = $('#xzdj').val();
                            var conditions = opts.conditions;
                            if (xzdj == 'Y' || xzdj == 'Z' || xzdj == 'C') {
                                conditions = conditions.replace(/lxdm/ig, "lddm");
                                conditions = conditions.replace(/lxbm/ig, "lddm");
                            } else if (opts.tableName == 'GIS_XZQH' || opts.tableName == 'GIS_LX') {
                                conditions = conditions.replace(/lxbm/ig, "lxdm");
                            }
                            return conditions;
                        },
                        conditionValues: function () {
                            var cons = opts.conditions.split(',');
                            var values = '';
                            for (var i = 0; i < cons.length; i++) {
                                var value = '';
                                if (cons[i] == 'xzqhbm') {
                                    if ($('#xzqhbm').combotree('tree').tree('getSelected') != null) {
                                        value = $('#xzqhbm').combotree('tree').tree('getSelected').id;
                                    } else {
                                        value = $('#xzqhbm').combotree('tree').tree('getRoot').id;
                                    }
                                } else {
                                    value = $('#' + cons[i]).val();
                                }
                                values += value;
                                if (i < cons.length - 1) {
                                    values += ",";
                                }
                            }
                            return values;
                        }
                    },
                    parse: function (data) {
                        var val = [];
                        val = $.map(eval(data), function (row) {
                            return {
                                data: row,
                                value: row,
                                result: row
                            };
                        });
                        return val;
                    },
                    formatItem: function (row, i, max) {
                        return '<div class="line">' + row + '</div>';
                    },
                    formatMatch: function (row, i, max) {//匹配的值
                        return row.split('-')[0].substring(0, 2);
                    },
                    formatResult: function (row) {
                        return row.split('-')[0].substring(0, 2);
                    }
                }).result(function (event, row, formatted) {
                    $(opts.id).val(row.split('-')[0]);
                    $('#lxmc').val();
                    $(opts.id).blur();
                });
            },

            autoName: function (options) {

                var defaults = {
                    url: '/restful/rest/xzqh/auto',
                    id: '',
                    width: 212,
                    max: 15,
                    tableName: '',
                    field: ''
                };

                var opts = $.extend(defaults, options);

                $(opts.id).autocomplete(opts.url, {
                    cacheLength: 1,
                    matchSubset: false,
                    selectFirst: true,
                    minChars: 0,
                    scroll: false,
                    delay: 500,
                    type: "get",
                    dataType: "json",
                    max: opts.max,
                    width: opts.width,
                    extraParams: {
                        field: opts.field,
                        tableName: function () {
                            var xzdj = $('#xzdj').val();
                            if (xzdj == 'Y' || xzdj == 'Z' || xzdj == 'C')  return 'GIS_NCLX';
                            else return opts.tableName;
                        },
                        value: function () {
                            var val = $(opts.id).val();
                            return val;
                        },
                        xzdj: function () {
                            var val = $('#xzdj').val();
                            if (val == null) {
                                val = "";
                            }
                            return val;
                        }
                    },
                    parse: function (data) {
                        var val = [];
                        val = $.map(eval(data), function (row) {
                            return {
                                data: row,
                                value: row,
                                result: row
                            };
                        });
                        return val;
                    },
                    formatItem: function (row, i, max) {
                        return '<div class="line">' + row + '</div>';
                    }
                });
            },

            /**
             * This method is used to jquery.ztree the encapsulation of the ajax request
             */
            xzqhTree: function (options) {

                var defaults = {
                    url: '/restful/rest/dist/tree',
                    id: '#xzqhbm'
                };

                var opts = $.extend(defaults, options);

                $(opts.id).combotree({
                    url: opts.url,
                    onLoadSuccess: function (node, data) {
                        var root = $(opts.id).combotree('tree').tree('getRoot').text;
                        $(opts.id).combotree('setValue', root);
                    }
                });
            },

            /**
             * list page
             */
            pageList: function (options) {
                var self = this;
                var defaults = {
                    zt: '',
                    url: '',
                    data: {},
                    table: '',
                    name: '',
                    height: 140,
                    column: {},
                    imgCode: ''
                };

                var opts = $.extend(defaults, options);

                $('#search_detail').hide();
                $('#search_list').show();
                $('#search_condition').hide();

                var datas = '';
                if (opts.data) {
                    var data = opts.data;
                    for (var key in data) {
                        datas += key + '=' + data[key] + '&';
                    }
                    datas = datas.substr(0, datas.length - 1);
                }

                $.ajax({
                    url: opts.url,
                    type: 'get',
                    cache: false,
                    async: false,
                    data: datas,
                    dataType: 'json',
                    success: function (obj) {
                        var map_id = '';
                        var where = [];
                        var count = obj.total;
                        $('.' + opts.zt + '-totle').text("共" + count + "条");
                        $('#count').val(count);
                        var list = '';
                        $('#' + opts.zt + '_list').html('');
                        if (obj != null && obj.rows.length != 0) {
                            for (var i = 0; i < obj.rows.length; i++) {
                                if (i == obj.rows.length - 1) {
                                    map_id += "id='" + obj.rows[i].id + "'";
                                } else {
                                    map_id += "id='" + obj.rows[i].id + "'" + " or ";
                                }
                                var name = Util.nullToWarp(obj.rows[i][opts.name]);
                                list += '<div class="' + opts.zt + '-lb-wrap" toggle="false" style="height:' + opts.height + 'px">'
                                + '<span>' + opts.imgCode + '</span> <span class="search_detail">详情&nbsp;&raquo;</span>'
                                + '<div class="search-id" style="display:none">' + obj.rows[i].id + '</div>'
                                + '<ul>'
                                + '<li title="' + name + '">' + name + '</li>';

                                var columns = opts.column;
                                for (key in columns) {
                                    var value = Util.nullToWarp(obj.rows[i][key]);
                                    if (key == 'lxfx' || key == 'xlfx') {
                                        value = self.sxxfx[value];
                                        list += '<li title="' + value + '">' + columns[key] + '：' + value + '</li>'
                                    } else {
                                        list += '<li title="' + value + '">' + columns[key] + '：' + value + '</li>'
                                    }
                                }

                                list += '</ul>'
                                + '</div>';
                                where.push("id='" + obj.rows[i].id + "'");
                                $('#' + opts.zt + '_list').html(list);
                            }
                            if (where.length > 0) {
                                if (self.queryShapeSubscirbe) {
                                    self.queryShapeSubscirbe.remove();
                                }
                                self.queryShapeSubscirbe = topic.subscribe("queryShapeComplated", function (evtObj) {
                                    //先取消事件绑定，取消之后再绑定
                                    $('.' + opts.zt + '-lb-wrap').unbind('click');
                                    $('.' + opts.zt + '-lb-wrap').bind("click", function () {
                                        var thisid = $(this).find('.search-id').html();
                                        self.currentGraphic = Util.hightlightGraphic(evtObj.table, {
                                            "attrName": "id",
                                            "attrValue": thisid
                                        });
                                        dzdtAppConfig.mapManager.centerGraphic(self.currentGraphic.geometry);
                                    });
                                });
                                Util.queryShape({
                                    layerName: opts.table,
                                    where: where.join(" OR ")
                                });
                            }
                        }
                    },
                    error: function () {
                        swal({
                            title: "系统出错!",
                            text: "请刷新页面，或联系管理员！",
                            type: "error",
                            confirmButtonText: '关闭'
                        });
                    }
                });
            },

            /**
             * detail page
             */
            pageDetail: function (options) {
                var defaults = {
                    id: '',
                    url: '',
                    name: '',
                    table: '',
                    column: {}
                };
                var opts = $.extend(defaults, options);
                $('#search_detail').show();
                $('#search_list').hide();
                $('#search_condition').hide();
                $.ajax({
                    url: opts.url,
                    type: 'get',
                    cache: false,
                    data: 'id=' + opts.id,
                    dataType: 'json',
                    success: function (obj) {

                        Util.queryShape({
                            layerName: opts.table,
                            where: "id='" + obj.id + "'"
                        });

                        var name = Util.nullToWarp(obj[opts.name]);
                        var list = '<span>&#xe621;</span>'
                            + '<ul>'
                            + '<li title="' + name + '">' + name + '</li>';

                        var columns = opts.column;
                        for (var key in columns) {
                            var value = Util.nullToWarp(obj[key]);
                            list += '<li title="' + value + '">' + columns[key] + '：' + value + '</li>'
                        }
                        list += '</ul>';
                        $("#search_detail_content").html(list);
                    },
                    error: function () {
                        swal({
                            title: "系统出错!",
                            text: "请刷新页面，或联系管理员！",
                            type: "error",
                            confirmButtonText: '关闭'
                        });
                    }
                });
            },
            /**
             * toggle show detail page
             */
            toggleDetail: function (options) {
                var self = this;
                var defaults = {
                    height: 140
                };
                var opts = $.extend(defaults, options);
                var height = opts.height + 'px';
                $(".search_detail").on("click", function () {
                    var lb = $(this).parent();
                    var toggle = lb.attr('toggle');
                    if (toggle === 'true') {
                        lb.attr('toggle', 'false').height(height);
                    } else {
                        lb.attr('toggle', 'true').height('');
                    }
                });
            }
        }
    }
);